package com.spark.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spark.common.core.api.SparkCommonApi;
import com.spark.common.core.entity.model.DictModel;
import com.spark.common.core.entity.model.DictModelMany;
import com.spark.common.core.entity.model.SelectTableModel;
import com.spark.common.core.entity.model.SelectTreeTableModel;
import com.spark.common.core.entity.online.OnlineDataSource;
import com.spark.common.core.entity.params.SelectTableParams;
import com.spark.common.core.entity.params.SelectTableTreeParams;
import com.spark.common.core.entity.params.ValidExistDataParams;
import com.spark.common.core.entity.system.*;
import com.spark.common.utils.DictUtils;
import com.spark.common.utils.ParamsUtils;
import com.spark.common.utils.TreeBuilderUtils;
import com.spark.modules.online.mapper.OnlineDataSourceMapper;
import com.spark.modules.system.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 系统通用API Service
 *
 * @author LYCHEE
 * @date 2025/2/20 09:41
 */
@Service
public class SparkCommonServiceImpl implements SparkCommonApi {

    @Resource
    private SysCommonMapper sysCommonMapper;
    @Resource
    private SysDictMapper sysDictMapper;
    @Resource
    private OnlineDataSourceMapper onlineDataSourceMapper;
    @Resource
    private SysParamsTypeMapper sysParamsTypeMapper;
    @Resource
    private SysLoginLogMapper sysLoginLogMapper;
    @Resource
    private SysOperateLogMapper sysOperateLogMapper;

    /**
     * 查询表中数据
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public List<SelectTableModel> querySelectTable(SelectTableParams params) {
        return sysCommonMapper.querySelectTable(params);
    }

    /**
     * 查询树表中数据
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public List<SelectTreeTableModel> querySelectTreeTable(SelectTableTreeParams params) {
        List<SelectTreeTableModel> treeTableModels = sysCommonMapper.querySelectTreeTable(params);
        // 处理为层级结构
        List<SelectTreeTableModel> buildTreeModels = new TreeBuilderUtils("id", params.getParentField(), "children")
                .buildTree(treeTableModels);
        if (StringUtils.isNotEmpty(params.getSortRankField())) {
            boolean sortWay = !StringUtils.isNotEmpty(params.getSortRankWay()) || !"DESC".equalsIgnoreCase(params.getSortRankWay());
            TreeBuilderUtils.sortTreeNodes(buildTreeModels, "sortRank", sortWay);
        }
        return buildTreeModels;
    }

    /**
     * 验证是否存在数据
     *
     * @param params 参数
     * @return 是否存在
     */
    @Override
    public boolean validExistData(ValidExistDataParams params) {
        List<String> ids = sysCommonMapper.validExistData(params);
        if (StringUtils.isNotEmpty(params.getRowId()) && !CollectionUtils.isEmpty(ids)) {
            return !ids.contains(params.getRowId());
        } else {
            return !CollectionUtils.isEmpty(ids);
        }
    }

    /**
     * 刷新字典缓存
     *
     * @param forceRefresh 强制刷新
     */
    @Override
    public void refreshDictCache(boolean forceRefresh) {
        if (forceRefresh){
            DictUtils.clearDictCache();
        }
        List<SysDict> dictList = sysDictMapper.queryAllDict();
        for (SysDict item : dictList) {
            List<SysDictItem> dictItems = item.getDictItems();
            if (!CollectionUtils.isEmpty(dictItems)){
                dictItems.forEach(dictItem -> {
                    dictItem.setCode(item.getDictCode());
                });
                DictUtils.setDictCache(item.getDictCode(), dictItems);
            }
        }
    }

    /**
     * 获取默认的数据源
     *
     * @return 默认数据源
     */
    @Override
    public OnlineDataSource queryDefaultDataSource() {
        LambdaQueryWrapper<OnlineDataSource> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OnlineDataSource::getIsDefault, 0);
        List<OnlineDataSource> onlineDataSources = onlineDataSourceMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(onlineDataSources)){
            return null;
        }
        return onlineDataSources.get(0);
    }

    /**
     * 通过ID获取数据源
     *
     * @param id 主键
     * @return 数据源
     */
    @Override
    public OnlineDataSource queryDataSourceById(String id) {
        return onlineDataSourceMapper.selectById(id);
    }

    /**
     * 刷新参数缓存
     *
     * @param forceRefresh 强制刷新
     */
    @Override
    public void refreshParamsCache(boolean forceRefresh) {
        if (forceRefresh){
            ParamsUtils.clearParamsCache();
        }
        List<SysParamsType> allParams = sysParamsTypeMapper.queryAllDict();
        for (SysParamsType item : allParams) {
            List<SysParams> paramItems = item.getParams();
            if (!CollectionUtils.isEmpty(paramItems)){
                ParamsUtils.setParamsCache(item.getBelongKey(), paramItems);
            }
        }
    }

    /**
     * 增加登录日志
     *
     * @param loginLog 登录信息
     */
    @Override
    public void addLoginLog(SysLoginLog loginLog) {
        loginLog.setCreateTime(new Date());
        sysLoginLogMapper.insert(loginLog);
    }

    /**
     * 增加操作日志
     *
     * @param operateLog 日志
     */
    @Override
    public void addHandlerLog(SysOperateLog operateLog) {
        operateLog.setCreateTime(new Date());
        sysOperateLogMapper.insert(operateLog);
    }

    /**
     * 字典表的 翻译，可批量
     *
     * @param table 表名
     * @param text  展示名
     * @param code  code
     * @param keys  多个用逗号分割
     * @return 字典翻译数据
     */
    @Override
    public List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys) {
        return sysDictMapper.queryTableDictTextByKeys(table, text, code, Arrays.asList(keys.split(",")));
    }

    /**
     * 普通字典的翻译，根据多个dictCode和多条数据，多个以逗号分割
     *
     * @param dictCodes 例如：user_status,sex
     * @param keys      例如：1,2,0
     * @return 字典翻译数据
     */
    @Override
    public Map<String, List<DictModel>> translateManyDict(String dictCodes, String keys) {
        List<String> dictCodeList = Arrays.asList(dictCodes.split(","));
        List<String> values = Arrays.asList(keys.split(","));
        List<DictModelMany> list = sysDictMapper.queryManyDictByKeys(dictCodeList, values);
        Map<String, List<DictModel>> dictMap = new HashMap(5);
        for (DictModelMany dict : list) {
            List<DictModel> dictItemList = dictMap.computeIfAbsent(dict.getDictCode(), i -> new ArrayList<>());
            dictItemList.add(new DictModel(dict.getValue(), dict.getText()));
        }
        //Map<String, List<DictModel>> enumRes = ResourceUtil.queryManyDictByKeys(dictCodeList, keys);
        //dictMap.putAll(enumRes);
        return dictMap;
    }
}
